package com.chenjun.common.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;

import com.chenjun.common.Constant;

public class UploadUtil {
	
	private static final Logger LOGGER = Logger.getLogger(UploadUtil.class);
	
	public static Map<String, String> doUpload(HttpServletRequest request){
		Map<String,String> map = new HashMap<String, String>();
		try {
			String savePath = "";
			System.out.println("request Map:"+request.getParameterMap());
			LOGGER.debug("request Map:"+request.getParameterMap());
	        Map<Object, Object> paramMap = buildParamMap(request.getParameterMap());
	        if (paramMap!=null && !paramMap.isEmpty()) {
	            // 当前路径
	            Object savePathObject= paramMap.get("dir");
	            if(savePathObject!=null){
	                savePath = savePathObject.toString();
	            }
	        }
			LOGGER.debug("savePath:"+savePath);
			String localPath = request.getSession().getServletContext().getRealPath("/file");
			System.out.println("保存路径:"+request.getSession().getServletContext().getRealPath("/file"));
			LOGGER.debug("保存路径:"+request.getSession().getServletContext().getRealPath("/file"));
			String filePath = FileUtil.multipartFileUpload(localPath, request);
			String serverPath = Constant.FILESERVER_HOST + "fileManager/upload.do";
			String result = "";
			LOGGER.debug(filePath);
			if (!StringUtil.isNull(filePath)) {
				result = FileUtil.copyFileToServer(savePath, localPath, filePath, serverPath);
			}
			LOGGER.debug("result:"+result);
			if(StringUtil.isNull(result)){
				map.put("success", "0");
				map.put("message", "上传失败");
			}else{
				JSONArray jsonArray = JSONArray.fromObject(result);
				map.put("success", "1");
	            map.put("message", "上传成功");
	            map.put("name", jsonArray.getJSONObject(0).getString("fileName"));
	            map.put("url", jsonArray.getJSONObject(0).getString("filePath"));
			}
		} catch (Exception e) {
			map.put("success", "0");
			map.put("message", "上传失败");
		}
		return map;
	}
	
	private static Map<Object, Object> buildParamMap(Map<String, String[]> requestMap) {
        Map<Object, Object> _map = new HashMap<Object, Object>();
        if (requestMap != null) {
            for (Object _key : requestMap.keySet()) {
                Object _obj = requestMap.get(_key);
                if (_obj instanceof String[]) {
                    _map.put(_key, ((String[]) _obj)[0]);
                } else {
                    _map.put(_key, _obj);
                }
            }
        }
        return _map;
    }

}
